<script setup>
import { getSiteList, getAdvert, getNearbySite } from '@/api/my';
import { debounce } from 'lodash';

// 地图相关响应式数据
const activeTab = ref('map'); // 初始显示地图
const latitude = ref(0);
const longitude = ref(0);
const scale = ref(15);
const markers = ref([]);
const siteDetail = reactive({});
const showModalStatus = ref(false);

//附近门店相关响应式数据
const scrollHeight = ref(0);
const dataList = ref([]);
const show = ref(false);
const isLoading = ref(false);
const page = ref(1);
const timer = ref(null);
const carouselList = ref([]);
const pageSize = ref(10);


//页面切换
const switchTab = async (tab) => {
  activeTab.value = tab;
  await initData();
};

// 获取页面高度
const setScrollHeight = () => {
  const windowHeight = uni.getSystemInfoSync().windowHeight;
  const windowWidth = uni.getSystemInfoSync().windowWidth;
  scrollHeight.value = (windowHeight * 750) / windowWidth - 90 - 30;
};

// 获取用户位置
const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (res) => {
        longitude.value = res.longitude;
        latitude.value = res.latitude;
        resolve(res);
      },
      fail: (err) => {
        uni.showModal({
          title: '提示',
          content: '未能获取当前位置,请在设置中授权位置信息',
          showCancel: false
        });
        reject(err);
      }
    });
  });
};

//获取网点列表
const initData = async () => {
  try {
    //const defaultLongitude = 115.50484; // 设置默认经度
    //const defaultLatitude = 38.84483; // 设置默认纬度
    const map = TXMapToBMap(longitude.value, latitude.value);
    const distance = getApp().globalData.distance || 5; // 默认值为5公里
    const total = getApp().globalData.total || 10; // 默认值为10
    const queryParam = {
      lng: map[0],
      lat: map[1],
      // lng:'115.50484',
      // lat: '38.84483',
      distance: Number(distance),
      total: Number(total)
    };

    let res = {};
    if (activeTab.value == 'map') {
      res = await getNearbySite(queryParam);
    } else {
      res = await getSiteList(queryParam);
    }

    console.log('---------->', res);
    if (res && res.data.length < 1) {
      show.value = true;
      return;
    }
    const markersData = res.data.map((site) => ({
      id: site.id,
      latitude: site.lat,
      longitude: site.lng,
      iconPath: '/static/images/icon_chardian.png',
      width: 30,
      height: 30,
      callout: {
        content: site.name,
        color: '#ffffff',
        fontSize: 12,
        borderRadius: 5,
        bgColor: '#4CAF50',
        borderWidth: 2,
        borderColor: '#ffffff',
        display: 'BYCLICK' //'BYCLICK'
      }
    }));
    markers.value = markersData;
    dataList.value = res.data;
    //totalItems.value = res.data.length;
    isLoading.value = false;
  } catch (error) {
    console.error('initData error:', error);
    isLoading.value = false;
  }
};

//腾讯地图转百度地图
const TXMapToBMap = (lng, lat) => {
  if (!lng || !lat) return [lng, lat];
  const x_pi = 3.14159265358979324;
  const x = parseFloat(lng);
  const y = parseFloat(lat);
  const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
  const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
  const newLng = (z * Math.cos(theta) + 0.0065).toFixed(5);
  const newLat = (z * Math.sin(theta) + 0.006).toFixed(5);
  return [Number(newLng), Number(newLat)];
};

// 百度坐标转腾讯坐标
const go = (lng, lat, name) => {
  const x_pi = (3.14159265358979324 * 3000.0) / 180.0;
  const x = lng - 0.0065;
  const y = lat - 0.006;
  const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  const gcjLon = z * Math.cos(theta);
  const gcjLat = z * Math.sin(theta);
  uni.openLocation({
    latitude: gcjLat,
    longitude: gcjLon,
    name: name
  });
};

// 地图中心点位置获取
const getMapCenter = () => {
  return new Promise((resolve) => {
    const mapCtx = uni.createMapContext('map');
    mapCtx.getCenterLocation({
      type: 'gcj02',
      success: (res) => {
        resolve(res);
      }
    });
  });
};

//地图坐标移动
const regionchange = debounce(async (e) => {
  if (e.type === 'end') {
    const centerLocation = await getMapCenter();
    if (centerLocation) {
      longitude.value = centerLocation.longitude;
      latitude.value = centerLocation.latitude;
      await initData();
    }
  }
}, 1000);

const showModal = (e) => {
  const markerId = e.detail.markerId;
  const marker = dataList.value.find((m) => m.id === markerId);
  const index = markers.value.findIndex((m) => m.id === markerId);
  if (marker && index != -1) {
    // Object.assign(siteDetail.value, marker);
    siteDetail.value = marker;
    siteDetail.value.iconPath = '/static/images/icon_box.png';
    markers.value[index].iconPath = '/static/images/icon_maker.png';
    console.log(markers.value[index]);
    showModalStatus.value = true;
  }
};

const hideModal = () => {
  console.log('取消');
  showModalStatus.value = false;
  markers.value.forEach((marker) => {
    if (marker.id === siteDetail.value.id) {
      marker.iconPath = '/static/images/icon_chardian.png';
    }
  });
};

// 跳转详情
const goSiteDetail = (id, unit, distance) => {
  uni.navigateTo({
    url: `/pages/siteDetail/siteDetail?siteid=$id}&distancecn=${distance}&unit=${unit}`
  });
};

const navigation = () => {
  uni.openLocation({
    latitude: siteDetail.value.lat,
    longitude: siteDetail.value.lng,
    name: siteDetail.value.tie,
    address: siteDetail.value.address
  });
};

//下拉加载更多
const lower = () => {
  if (!isLoading.value) {
    isLoading.value = true;
    page.value += 1;
    clearTimeout(timer.value);
    timer.value = setTimeout(() => {
      initData(true);
    }, 1500); // 设置节流时间
  }
};

// 获取广告信息
// const getAdvertData = async () => {
//   try {
//     const res = await getAdvert();
//     console.log('--------->', res);
//     carouselList.value = res.data;
//   } catch (error) {
//     console.error('getAdvertData error:', error);
//   }
// };

onMounted(async () => {
  setScrollHeight();
  await getUserLocation();
  // getAdvertData();
  await initData();
});
</script>

<template>
  <view class="container">
    <view class="tab-bar">
      <view :class="['tab-item', activeTab === 'map' ? 'active' : '']" @tap="switchTab('map')">地图</view>
      <view :class="['tab-item', activeTab === 'stores' ? 'active' : '']" @tap="switchTab('stores')">附近门店</view>
    </view>
    <!--   @regionchange="regionchange" -->
    <view v-if="activeTab === 'map'" class="content">
      <map
        id="map"
        class="map"
        :longitude="longitude"
        :latitude="latitude"
        :scale="scale"
        :markers="markers"
        show-location="true"
        @regionchange="regionchange"
        @markertap="showModal"
      />
      <cover-view class="commodity_screen" v-if="showModalStatus" @tap="hideModal"></cover-view>
      <cover-view v-if="showModalStatus" class="commodity_attr_box">
        <cover-view class="placeBox">
          <cover-view class="box1">
            <cover-view class="box3" @tap="goSiteDetail(siteDetail.value.id, siteDetail.value.unit, siteDetail.value.distance)">
              <cover-view class="rentbox" style="height: 150rpx; display: flex">
                <cover-image style="width: 104rpx; height: 104rpx" :src="siteDetail.value.iconPath"></cover-image>
                <cover-view class="placeViewLt">
                  <cover-view class="viewTitle">{{ siteDetail.value.name }}</cover-view>
                  <cover-view class="viewAddr" style="margin-top: 7rpx">{{ siteDetail.value.address }}</cover-view>
                </cover-view>
              </cover-view>
              <cover-view class="box6" style="height: 150rpx">
                <cover-view class="work">
                  <cover-view class="workTime">营业时间</cover-view>
                  <cover-view class="workAspect" style="padding-top: 20rpx">{{ siteDetail.value.open_time }}</cover-view>
                </cover-view>
                <cover-view>
                  <cover-view class="workTime">机柜情况{{}}</cover-view>
                  <cover-view class="workAspect" style="padding-top: 20rpx; display: flex; justify-content: center; align-items: center">
                    <cover-view :style="{ color: siteDetail.value.borrow ? '#10C0B9' : '#616169' }">{{ siteDetail.value.borrow ? '可租借' : '不可租借' }}</cover-view>
                    <cover-view :style="{ color: siteDetail.value.empty ? '#10C0B9' : '#616169', marginLeft: '12rpx' }">
                      {{ siteDetail.value.empty ? '可归还' : '不可还' }}
                    </cover-view>
                  </cover-view>
                </cover-view>
              </cover-view>
            </cover-view>
            <cover-view class="box5"></cover-view>
            <cover-view class="box4">
              <cover-image @tap="navigation" style="width: 136rpx; height: 136rpx; margin-left: 6rpx; margin-top: 14rpx" src="/static/images/icon_navigation.png"></cover-image>
              <cover-view class="distance">
                <cover-view class="distance">{{ siteDetail.value.distance > 1 ? siteDetail.value.distance.toFixed(2) : siteDetail.value.distance.toFixed(2) * 1000 }}</cover-view>
                <cover-view class="unit">{{ siteDetail.value.distance > 1 ? '千米' : '米' }}</cover-view>
              </cover-view>
            </cover-view>
          </cover-view>
        </cover-view>
      </cover-view>

      <view class="marker">
        <view>
          <image src="/static/images/icon_marker.png" mode="widthFix" class="img"></image>
        </view>
      </view>
    </view>

    <view v-if="activeTab === 'stores'" class="content">
      <scroll-view scroll-y @scrolltolower="lower" :style="{ height: scrollHeight + 'rpx' }">
        <uni-card class="footer_card" v-for="(item, index) in dataList" :key="item.id + '-' + index" @click="go(item.lng, item.lat, item.name)">
          <view class="text_container">
            <text class="lately" v-if="index === 0">最近</text>
            <text class="title">{{ item.name }}</text>
            <view class="title_2">{{ item.address }}</view>
            <view class="title_2">营业时间: {{ item.open_time }}</view>
          </view>
          <view class="text_status">
            <view class="status_container">
              <text :style="{ color: item.borrow ? '#10C0B9' : '#616169' }" class="status">{{ item.borrow ? '可租借' : '不可租借' }}</text>
              <text :style="{ color: item.empty ? '#10C0B9' : '#616169' }" class="status">{{ item.empty ? '可归还' : '不可还' }}</text>
            </view>
            <view class="text_distance">
              <text>距离{{ item.distanceCn }}</text>
            </view>
          </view>
        </uni-card>
        <view class="hint" v-if="show && dataList.length === 0" style="margin-top: 40rpx; text-align: center; font-size: 34rpx">暂无数据哦!</view>
        <view v-if="isLoading" class="loading" style="text-align: center">加载中...</view>
      </scroll-view>
    </view>
  </view>
</template>
<style lang="scss">
// 定义变量
$primary-color: #ff6700;
$secondary-color: #889dba;
$background-color: #e8f1f8;
$font-color: #333;
$light-color: #ececec;

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin text-style($size, $weight: normal, $color: $font-color) {
  font-size: $size;
  font-weight: $weight;
  color: $color;
}
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: $light-color;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.tab-bar {
  display: flex;
  justify-content: space-around;
  background-color: #f5f5f5;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px;
  cursor: pointer;
}

.active {
  background-color: #4caf50;
  color: white;
}

.content {
  flex: 1;
  overflow: auto;
}

.map {
  width: 100%;
  height: 100%;
}

.store-list {
  padding: 10px;
}

.store-item {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}
.uni-card {
  margin: 0rpx 20rpx !important;
  border-radius: 20rpx !important;
}
.footer_card {
  padding: 5rpx;

  .text_container {
    padding-left: 120rpx;

    .lately {
      padding: 8rpx;
      margin-right: 10rpx;
      border: 2rpx solid $primary-color;
      border-radius: 8rpx;
      @include text-style(22rpx, normal, $primary-color);
    }

    .title {
      display: inline-block;
      vertical-align: text-top;
      @include text-style(30rpx, bold);
    }

    .title_2 {
      margin-top: 15rpx;
      @include text-style(26rpx);
    }
  }

  .text_status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;

    .status_container {
      flex: 1;
      margin-top: 20rpx;
      width: 80rpx;

      .status {
        padding: 16rpx;
        @include text-style(24rpx, normal, $secondary-color);
        background-color: $light-color;
        box-sizing: border-box;

        &:hover {
          color: $primary-color;
        }
      }
    }

    .text_distance {
      margin-top: 20rpx;
      @include text-style(26rpx, bold);
    }
  }

  .loading {
    padding: 20rpx 0;
    font-size: 30rpx;
    color: $secondary-color;
  }
}

.commodity_attr_box {
  position: fixed;
  height: 465rpx;
  width: 750rpx;
  bottom: 0rpx;
  padding-bottom: 0rpx;
  z-index: 9;
  display: flex;
  justify-content: center;
}
.commodity_screen {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: #000;
  opacity: 0.2;
  overflow: hidden;
  z-index: 3;
  color: #fff;
}
.placeBox {
  width: 690rpx;
  height: 386rpx;
  border-radius: 16rpx;
}
.box1 {
  height: 300rpx;
  display: flex;
}
.box3 {
  width: 534rpx;
  height: 300rpx;
  background-color: #ffffff;
}
.box5 {
  width: 6rpx;
  background: rgba(248, 248, 251, 1);
  display: flex;
  justify-content: center;
}
.box4 {
  width: 152rpx;
  height: 300rpx;
  background-color: #ffffff;
}
.box6 {
  height: 150rpx;
  display: flex;
  justify-content: space-around;
  margin-top: 33rpx;
}
.workTime {
  font-size: 24rpx;
  font-family: OPPOSans;
  font-weight: bold;
  color: rgba(97, 97, 105, 1);
}
.workAspect {
  font-size: 24rpx;
  font-family: OPPOSans;
  font-weight: bold;
}
.rentbox {
  padding-top: 23rpx;
  padding-left: 28rpx;
}
.distance {
  font-size: 50rpx;
  font-family: OPPOSans;
  font-weight: bold;
  color: rgba(38, 38, 38, 1);
  line-height: 56rpx;
  text-align: center;
}
.unit {
  font-size: 24rpx;
  font-family: OPPOSans;
  font-weight: bold;
  color: #616169;
  line-height: 42rpx;
}
.marker {
  /* position: fixed; */
  position: absolute;
  bottom: 50%;
  left: 50%;
  margin: 0 0 -63rpx -19rpx;
  z-index: 0;
}
.marker .img {
  width: 35rpx;
  height: auto;
}
.placeViewLt {
  display: inline-block;
  vertical-align: middle;
  padding-left: 31rpx;
  width: 380rpx;
}
.viewTitle {
  margin-top: 10rpx;
  font-size: 28rpx;
  font-family: OPPOSans;
  font-weight: bold;
  color: rgba(38, 38, 38, 1);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.viewAddr {
  font-size: 24rpx;
  font-family: OPPOSans;
  font-weight: 400;
  color: rgba(97, 97, 105, 1);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
